package com.erp.config;


import com.erp.shiro.impl.ShiroRealmImpl;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
        //1、创建过滤器工厂
        ShiroFilterFactoryBean filterFactory = new ShiroFilterFactoryBean();
        //2、设置安全管理器
        filterFactory.setSecurityManager(securityManager);
        //4、设置过滤器集合
        /*
          设置所有过滤器，使用有顺序的map
           key->拦截url地址
           value-> 过滤器类型
         */
        Map<String, String> map = new LinkedHashMap<>();
        //静态资源允许匿名访问:"anon"
        map.put("/user/login", "anon");
        map.put("/user/sendMsg", "anon");
        map.put("/user/register", "anon");
        map.put("/backend/api/**","anon");
        map.put("/backend/images/**","anon");
        map.put("/backend/js/**","anon");
        map.put("/backend/page/login/login.html","anon");
        map.put("/backend/plugins/**","anon");
        map.put("/backend/styles/**","anon");
        //除了匿名访问的资源,其它都要认证("authc")后访问
        map.put("/**", "authc");    //假如需要实现记住我功能，这里的过滤器标识使用user
        filterFactory.setFilterChainDefinitionMap(map);
        filterFactory.setLoginUrl("/backend/page/login/login.html");
        return filterFactory;
    }

    @Bean
    public DefaultWebSecurityManager getSecurityManager(ShiroRealmImpl realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean(name="Realm")
    public ShiroRealmImpl userRealm(){
        return new ShiroRealmImpl();
    }

    /**
     * 开启注解方式控制访问url
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

}
